<template>
    <div class="">
        <el-dialog :title="isAdd ? '添加商品管理' : '编辑商品管理'" :visible.sync="isShow" :before-close="cancel" center
            @opened="createEditor">
            <el-form :model="goodslist" :rules="rules" ref="goodsInfo">
                <el-form-item label="一级分类" :label-width="formLabelWidth" prop="first_cateid">
                    <el-select placeholder="请选择" v-model="goodslist.first_cateid" @change="changeCate(false)">
                        <el-option v-for="item in catelist" :key="item.id" :value="item.id"
                            :label="item.catename"></el-option>

                    </el-select>
                </el-form-item>
                <el-form-item label="二级分类" :label-width="formLabelWidth" prop="second_cateid">
                    <el-select placeholder="请选择" v-model="goodslist.second_cateid">
                        <el-option v-for="item in secondCateArr" :key="item.id" :value="item.id"
                            :label="item.catename"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="商品名称" :label-width="formLabelWidth" prop="goodsname">
                    <el-input autocomplete="off" v-model="goodslist.goodsname"></el-input>
                </el-form-item>
                <el-form-item label="商品价格" :label-width="formLabelWidth" prop="price">
                    <el-input autocomplete="off" v-model="goodslist.price"></el-input>
                </el-form-item>
                <el-form-item label="市场价格" :label-width="formLabelWidth" prop="market_price">
                    <el-input autocomplete="off" v-model="goodslist.market_price"></el-input>
                </el-form-item>
                <el-form-item label="图片" :label-width="formLabelWidth">
                    <el-upload action="#" list-type="picture-card" :on-preview="onPreview" :on-remove="handleRemove"
                        :auto-upload="false" :on-change="onChange" :file-list="fileList" :limit="1"
                        :on-exceed="onExceed">
                        <i class="el-icon-plus"></i>
                    </el-upload>
                    <el-dialog :visible.sync="dialogVisible">
                        <img width="100%" :src="dialogImageUrl" alt="" />
                    </el-dialog>
                </el-form-item>
                <el-form-item label="商品规格" :label-width="formLabelWidth" prop="specsid">
                    <el-select placeholder="请选择" v-model="goodslist.specsid" @change="changeSpecs(false)">
                        <el-option v-for="item in specsArr" :key="item.id" :value="item.id"
                            :label="item.specsname"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="属性规格" :label-width="formLabelWidth" prop="specsattr">
                    <el-select v-model="goodslist.specsattr" placeholder="请选择" multiple>
                        <el-option v-for="item in attrArr" :key="item" :value="item" :label="item"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="是否新品" :label-width="formLabelWidth">

                    <el-radio :label="1" v-model="goodslist.isnew">是</el-radio>
                    <el-radio :label="2" v-model="goodslist.isnew">否</el-radio>

                </el-form-item>
                <el-form-item label="是否热卖" :label-width="formLabelWidth">
                    <el-radio v-model="goodslist.ishot" :label="1">是</el-radio>
                    <el-radio v-model="goodslist.ishot" :label="2">否</el-radio>
                </el-form-item>
                <el-form-item label="商品描述" :label-width="formLabelWidth">
                    <div id="editor"></div>
                </el-form-item>
                <el-form-item label="状态" :label-width="formLabelWidth">
                    <el-switch v-model="goodslist.status" active-color="#13ce66" inactive-color="#ff4949"
                        :active-value="1" :inactive-value="2">
                    </el-switch>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="cancel">取 消</el-button>
                <el-button type="primary" @click="confirm">确 定</el-button>
            </div>
        </el-dialog>

    </div>
</template>
<script>
import { goodsAdd, getgoodsInfo, goodsEdit, specsList } from '../../request/api'
import { mapGetters, mapActions } from 'vuex';
import E from 'wangeditor'
export default {
    props: ['isShow', 'isAdd'],
    data() {
        return {
            goodslist: {
                first_cateid: "", //一级分类编号
                second_cateid: "", //二级分类编号
                goodsname: "", //商品名称
                price: "", //商品价格
                market_price: "", //市场价格
                img: "", //商品图片（文件）
                description: "", //商品描述
                specsid: "", //商品规格编号
                specsattr: "", //商品规格属性
                isnew: 1, //是否新品1是2不是
                ishot: 1, //是否热卖1是2不是
                status: 1, //状态1正常2禁用
            },
            formLabelWidth: '120px',
            dialogVisible: false,
            dialogImageUrl: '',
            fileList: [],
            rules: {
                goodsname: [
                    { required: true, message: "请输入商品名称", trigger: "blur" },
                    {
                        min: 2,
                        max: 15,
                        message: "长度在 2 到 15 个字符",
                        trigger: "blur",
                    },
                ],
                price: [{ required: true, message: "请输入商品价格", trigger: "blur" }],
                market_price: [
                    { required: true, message: "请输入市场价格", trigger: "blur" },
                ],
                first_cateid: [
                    { required: true, message: "请选择一级分类", trigger: "change" },
                ],
                second_cateid: [
                    { required: true, message: "请选择二级分类", trigger: "blur" },
                ],
                specsid: [
                    { required: true, message: "请选择商品规格", trigger: "change" },
                ],
                specsattr: [
                    { required: true, message: "请选择规格属性", trigger: "blur" },
                ],
            },
            secondCateArr: [], //二级分类数组
            specsArr: [], //规格列表
            attrArr: [], //规格属性
            editor: null,//编辑器初始值
        }
    },
    computed: {
        ...mapGetters({
            catelist: 'classify/getCate'
        })
    },
    mounted() {
        console.log(this.catelist);
        this.getCateAction();
        this.getSpecs();
    },
    methods: {
        // 编辑器
        createEditor() {
            // 初始化
            this.editor = new E('#editor')
            // 创建
            this.editor.create()
            // 赋值初始值
            this.editor.txt.html(this.goodslist.description)
        },
        // 获取商品规格
        getSpecs() {
            specsList().then((res) => {
                this.specsArr = res.list
            })
        },
        ...mapActions({
            getCount: 'goods/getCountAction',
            getGoodsList: 'goods/getGoodsListAction',
            getCateAction: 'classify/changeCateAction'
        }),
        // 切换一级分类获取二级分类
        changeCate(n) {
            let index = this.catelist.findIndex(
                (item) => this.goodslist.first_cateid == item.id
            );
            this.secondCateArr = this.catelist[index].children
            // 清空二级分类双向数据绑定值
            if (!n) {
                this.goodslist.second_cateid = ''
            }
        },
        changeSpecs(n) {
            let index = this.specsArr.findIndex(
                (item) => this.goodslist.specsid == item.id
            );
            this.attrArr = this.specsArr[index].attrs
            if (!n) {
                this.goodslist.specsattr = []
            }
        },
        onExceed(files, fileList) {
            this.$message.warning(`当前限制选择1个文件,本次选择了${files.length}个文件,共选择了${files.length + fileList.length}个文件`)
        },
        onPreview(file) {
            this.dialogImageUrl = file.url;
            this.dialogVisible = true
        },
        handleRemove(file, fileList) {
            console.log(file, "移除", fileList);
            this.goodslist.img = ''
        },
        onChange(file, fileList) {
            this.goodslist.img = file.raw
        },
        cancel() {
            this.$emit('cancel', false)
            this.reset()
        },
        reset() {
            this.goodslist = {
                first_cateid: "",
                second_cateid: "",
                goodsname: "",
                price: "",
                market_price: "",
                img: "",
                description: "",
                specsid: "",
                specsattr: "",
                isnew: 1,
                ishot: 1,
                status: 1,
            };
            //调用清空验证的方法
            this.$refs.goodsInfo.resetFields();
            this.fileList = [];
            // 销毁编辑器
            this.editor.destroy()
        },
        lookup(id) {
            getgoodsInfo({ id }).then((res) => {
                if (res.code == 200) {
                    this.goodslist = res.list;
                    this.goodslist.id = id
                    this.fileList = this.goodslist.img ? [{ url: this.goodslist.img }] : []
                    this.goodslist.specsattr = this.goodslist.specsattr.split(",");
                    this.changeCate(true)
                    this.changeSpecs(true)
                    // 给富文本编辑器设置内容
                    this.editor.txt.html(this.goodslist.description)
                } else {
                    this.$message.error(res.msg)
                }
            })
        },
        confirm() {

            this.$refs.goodsInfo.validate((valid) => {
                if (valid) {
                    this.goodslist.specsattr = this.goodslist.specsattr.join(",");
                    this.goodslist.description = this.editor.txt.html()

                    if (this.isAdd) {
                        console.log(this.goodslist, '表单')
                        goodsAdd(this.goodslist).then((res) => {
                            console.log(res, '///');
                            if (res.code == 200) {

                                this.cancel()
                                this.getCount();
                                this.getGoodsList()
                                this.$message.success(res.msg)
                            } else {
                                this.$message.error(res.msg)
                            }
                        })
                    } else {

                        goodsEdit(this.goodslist).then((res) => {
                            if (res.code == 200) {
                                this.cancel()
                                this.getCount()
                                this.getGoodsList()
                                this.$message.success(res.msg)
                            } else {
                                this.$message.error(res.msg)
                            }
                        })
                    }
                } else {
                    this.$message.error('验证失败')
                    return false
                }
            })
        }
    }
}
</script>
<style scoped lang="scss">

</style>